package com.bml.architect.framework.protocol.http;

import com.alibaba.fastjson.JSONObject;
import com.bml.architect.framework.Invocation;
import com.bml.architect.framework.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HttpServerHandler {


    public void handler(HttpServletRequest request, HttpServletResponse response) {

        try {

           // Invocation invocation = JSONObject.parseObject(request.getInputStream(), Invocation.class);
            ObjectInputStream os = new ObjectInputStream(request.getInputStream());
            Invocation invocation = (Invocation) os.readObject();
            System.out.println(invocation);
            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            Class<?> register = LocalRegister.getRegister(interfaceName);
            Method method = register.getMethod(methodName, invocation.getParamTypes());
            String result = (String) method.invoke(register.newInstance(), invocation.getParams());
            IOUtils.write(result,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
}
